﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Windows.Media;
using System.Media;
using Styx.WoWInternals;

namespace ShutUp_AIML
{
    public partial class SettingsForm : Form
    {
        public SettingsForm()
        {
            InitializeComponent();
        }

        private readonly ShutUp_AIML _ShutUp = new ShutUp_AIML();
        private static Styx.WoWInternals.WoWObjects.LocalPlayer Me { get { return Styx.StyxWoW.Me; } }
        //private string[,] specificAnswer;
        private void SettingsForm_Load(object sender, EventArgs e)
        {
            try
            {
                VersionLabel.Text = "v" + _ShutUp.Version.ToString();
                BarryD.Image = Image.FromFile(Application.StartupPath + "\\Plugins\\ShutUpAIML\\Forms\\BarryDurex");
                Icon = ChatHelper.convertToIcon(BarryD.Image, System.Drawing.Color.Empty);

                chb_NotifyIcon.Checked = ShutUpSettings.Instance.useNotifyIcon;

                chb_saveLog.Checked = ShutUpSettings.Instance.saveLog;

                #region Friends & Guild Tab
                chb_answerFriends.Checked = ShutUpSettings.Instance.answerWisper_Friends;
                chb_softIgnoFriends.Checked = ShutUpSettings.Instance.softIgnoFriend;
                softIgnoAfter.Value = ShutUpSettings.Instance.softIgnoAfter;
                chb_FriendList1.Checked = ShutUpSettings.Instance.UseFriedlist1;
                chb_guildMaster.Checked = ShutUpSettings.Instance.UseGuildMaster;
                chb_guildMembers.Checked = ShutUpSettings.Instance.UseGuildMembersList;
                chb_guildOfficers.Checked = ShutUpSettings.Instance.UseGuildOffisList;
                chb_inGameFriends.Checked = ShutUpSettings.Instance.UseInGameFriedlist;
                chb_BNetFriends.Checked = ShutUpSettings.Instance.UseBNetFriedlist;

                string _gRank = Lua.GetReturnVal<string>("return GuildControlGetRankName(1);", 0);
                if (_gRank != "0")
                {
                    chb_guildMaster.Text = _gRank;
                    _gRank = Lua.GetReturnVal<string>("return GuildControlGetRankName(2);", 0);
                    chb_guildOfficers.Text = _gRank + "  (Rank 2)";
                }


                friendsList1.Lines = ShutUpGlobalSettings.Instance.FriendList1;
                inGameFriendsList.Lines = FriendsList.inGameFriends.ToArray();
                guildMaster.Text = FriendsList.guildMaster;
                guildOfficersList.Lines = FriendsList.guildOffis.ToArray();
                guildMembersList.Lines = FriendsList.guildMembers.ToArray();
                BNetFriendsList.Lines = FriendsList.BNetFriends.ToArray();
                #endregion

                #region Sound Tab
                lb_SoundFiles.Items.Clear();
                if (ShutUpGlobalSettings.Instance.soundFiles != null)
                    lb_SoundFiles.Items.AddRange(ShutUpGlobalSettings.Instance.soundFiles);

                update_cmb_sound();

                chb_soundOn_Friends.Checked = ShutUpSettings.Instance.SoundByFriend;
                chb_soundOn_unknown.Checked = ShutUpSettings.Instance.SoundByUnknown;
                chb_soundOn_myName.Checked = ShutUpSettings.Instance.SoundByMyName;
                chb_sound_ExternalPlayer_Friends.Checked = ShutUpSettings.Instance.useExternalPlayer_Friends;
                chb_sound_ExternalPlayer_unknown.Checked = ShutUpSettings.Instance.useExternalPlayer_unknown;
                chb_sound_ExternalPlayer_myName.Checked = ShutUpSettings.Instance.useExternalPlayer_myName;
                cmb_sound_Friends.SelectedItem = ShutUpSettings.Instance.selectedSoundFriends;
                cmb_sound_unknown.SelectedItem = ShutUpSettings.Instance.selectedSoundUnknown;
                cmb_sound_myName.SelectedItem = ShutUpSettings.Instance.selectedSoundMyName;

                soundLoop.Value = ShutUpSettings.Instance.SoundLoop;
                soundLoopEvery.Value = ShutUpSettings.Instance.SoundLoopEvery;
                #endregion

                #region Answer Tab

                lb_randomAnswer.Items.Clear();
                if (ShutUpGlobalSettings.Instance.randomAnswer != null)
                    lb_randomAnswer.Items.AddRange(ShutUpGlobalSettings.Instance.randomAnswer);



                chb_answerFriends2.Checked = ShutUpSettings.Instance.answerWisper_Friends;
                chb_myName_answer2.Checked = ShutUpSettings.Instance.myName_answer;
                chb_answerWhisper_unknown.Checked = ShutUpSettings.Instance.answerWisper_unknown;
                answerAfterSec.Value = ShutUpSettings.Instance.answerAfterSec;
                rb_ignoAll.Checked = ShutUpSettings.Instance.ignoAll;
                rb_ignoAfterX.Checked = ShutUpSettings.Instance.ignoXW;
                rb_noIgno.Checked = ShutUpSettings.Instance.ignoNo;
                softIgnoAfter.Value = ShutUpSettings.Instance.softIgnoAfter;
                chb_ingameIgno.Checked = ShutUpSettings.Instance.ingameIgno;
                chb_Answer_useRnd.Checked = ShutUpSettings.Instance.answerUseRnd;
                chb_Answer_AIML.Checked = ShutUpSettings.Instance.answerUseAIML;

                #endregion

                #region myName Tab
                if (ShutUpGlobalSettings.Instance.myName_list != null)
                    lb_myName_all.Items.AddRange(ShutUpGlobalSettings.Instance.myName_list);

                if (ShutUpSettings.Instance.myName_list != null)
                    lb_myName_this.Items.AddRange(ShutUpSettings.Instance.myName_list);

                if (!lb_myName_this.Items.Contains(Me.Name))
                    lb_myName_this.Items.Add(Me.Name);

                chb_myName_BG.Checked = ShutUpGlobalSettings.Instance.myName_check_bg;
                chb_myName_guild.Checked = ShutUpGlobalSettings.Instance.myName_check_guild;
                chb_myName_party.Checked = ShutUpGlobalSettings.Instance.myName_check_party;
                chb_myName_raid.Checked = ShutUpGlobalSettings.Instance.myName_check_raid;
                chb_myName_say.Checked = ShutUpGlobalSettings.Instance.myName_check_say;
                chb_myName_yell.Checked = ShutUpGlobalSettings.Instance.myName_check_yell;
                chb_myName_answer.Checked = ShutUpSettings.Instance.myName_answer;
                chb_myName_showPopUp.Checked = ShutUpGlobalSettings.Instance.myName_showPopUp;

                #endregion

                #region Securities

                chb_GManswerGMwhisperCheck.Checked = ShutUpGlobalSettings.Instance.GM_Answer;
                chb_GMsoundByGMwhisperCheck.Checked = ShutUpGlobalSettings.Instance.GM_PlaySound;
                chb_GMlogoutByGMwhisperCheck.Checked = ShutUpGlobalSettings.Instance.GM_Logout;
                chb_GMextPlayer.Checked = ShutUpGlobalSettings.Instance.GM_ExtPlayer;
                if(GMAlarmMessage.Instance.Messages != null)
                {
                    lbox_GMmsg.Items.Clear();
                    lbox_GMmsg.Items.AddRange(GMAlarmMessage.Instance.Messages);
                }
                //tb_GManswerText.Text = ShutUpGlobalSettings.Instance.GM_AnswerText; // old stuff

                #endregion

                LoadLog();
            }
            catch (Exception ex)
            { ShutUp_AIML.dlog("SettingsForm_Load \n\n{0}", ex); }
        }
        
        #region Log Tab
        private void LoadLog()
        {
            try
            {
                string strFileContents = File.ReadAllText(ShutUp_AIML.ShutUpLogLocation);
                tbLog.AppendText(strFileContents);
                tbLog.ScrollToCaret();
            }
            catch (Exception ex)
            {
                //_ShutUp.dlog("Can not load Logfile! \n\n{0}", ex);
                ShutUp_AIML.dlog("create log file ..");
                File.Create(ShutUp_AIML.ShutUpLogLocation);
                System.Threading.Thread.Sleep(300);
            }
        }

        private void btn_clearLog_Click(object sender, EventArgs e)
        {
            try
            {
                File.Delete(ShutUp_AIML.ShutUpLogLocation);
                File.Create(ShutUp_AIML.ShutUpLogLocation);
                System.Threading.Thread.Sleep(300);
                this.tbLog.Text = string.Empty;
            }
            catch (Exception ex)
            {
                ShutUp_AIML.dlog("Can not clear Logfile! \n\n{0}", ex);
            }
        }
        #endregion

        #region Sound Tab
        private void update_cmb_sound()
        {
            try
            {
                string[] standartSound = new string[] {
            "bing sound", "beep.wav", "boing.wav", "canwedo.wav", "elephant.wav",
            "himan.wav", "murloc.wav", "scream.wav", "siren1.wav", "snore.wav", "youagain.wav" };

                List<string> _sounds = new List<string>();
                _sounds.AddRange(standartSound);

                if (lb_SoundFiles.Items.Count != 0)
                    foreach (var file in lb_SoundFiles.Items)
                    {
                        string[] _f = file.ToString().Split('\\');
                        _sounds.Add(_f[_f.Length - 1]);
                    }

                cmb_sound_unknown.Items.Clear();
                cmb_sound_Friends.Items.Clear();
                cmb_sound_myName.Items.Clear();
                cmb_sound_unknown.Items.AddRange(_sounds.ToArray());
                cmb_sound_Friends.Items.AddRange(_sounds.ToArray());
                cmb_sound_myName.Items.AddRange(_sounds.ToArray());
            }
            catch (Exception ex)
            { ShutUp_AIML.dlog("update_cmb_sound \n\n{0}", ex); }
        }

        private void btn_soundTest_Click(object sender, EventArgs e)
        {
            string caseSwitch = sender.ToString().Split(':')[1];
            string selectedItem = string.Empty;
            bool _externalPlayer = false;

            switch (caseSwitch)
            {
                case " sound test 1":
                    selectedItem = cmb_sound_unknown.SelectedItem.ToString();
                    _externalPlayer = chb_sound_ExternalPlayer_unknown.Checked;
                    break;
                case " sound test 2":
                    selectedItem = cmb_sound_Friends.SelectedItem.ToString();
                    _externalPlayer = chb_sound_ExternalPlayer_Friends.Checked;
                    break;
                case " sound test 3":
                    selectedItem = cmb_sound_myName.SelectedItem.ToString();
                    _externalPlayer = chb_sound_ExternalPlayer_myName.Checked;
                    break;
                default:
                    break;
            }

            if (selectedItem == "bing sound")
            {
                System.Media.SystemSounds.Beep.Play();
                System.Media.SystemSounds.Beep.Play();
            }
            else if (File.Exists(Application.StartupPath + "\\Plugins\\ShutUpAIML\\Sounds\\" + selectedItem))
            {
                if (_externalPlayer)
                    System.Diagnostics.Process.Start(Application.StartupPath + "\\Plugins\\ShutUpAIML\\Sounds\\" + selectedItem);
                else
                    new SoundPlayer(Application.StartupPath + "\\Plugins\\ShutUpAIML\\Sounds\\" + selectedItem).Play();
            }
            else if (lb_SoundFiles.Items.Contains(selectedItem))
            {
                foreach (string file in lb_SoundFiles.Items)
                {
                    if (file.Contains(selectedItem))
                    { selectedItem = file; break; }
                }

                if (_externalPlayer)
                    System.Diagnostics.Process.Start(selectedItem);
                else
                    new SoundPlayer(selectedItem).Play();
            }
        }

        private void btn_searchFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.tb_WaveLocation.Text = openFileDialog1.FileName;
            }
        }

        private void btn_addFile_Click(object sender, EventArgs e)
        {
            if(tb_WaveLocation.Text == "C:\\MyFolder\\MyWave.wav ")
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    this.tb_WaveLocation.Text = openFileDialog1.FileName;
                }
                else { return; }
            }
            lb_SoundFiles.Items.Add(tb_WaveLocation.Text);
            update_cmb_sound();
        }

        private void btn_removeFile_Click(object sender, EventArgs e)
        {
            if (lb_SoundFiles.Items.Count == 0 || lb_SoundFiles.SelectedItem == null)
                return;

            lb_SoundFiles.Items.Remove(lb_SoundFiles.SelectedItem);
            update_cmb_sound();
        }
        #endregion

        #region Friends & Guild Tab
        private void btn_refreshFriendsList_Click(object sender, EventArgs e)
        {
            this.UseWaitCursor = true;
            if (MessageBox.Show("in big guilds, it may take a long time!", "Watch out!", MessageBoxButtons.OKCancel) != DialogResult.OK)
                return;

            FriendsList.Update();
            System.Threading.Thread.Sleep(500);
            while (FriendsList.newThread.IsAlive)
                System.Threading.Thread.Sleep(1000);

            inGameFriendsList.Lines = FriendsList.inGameFriends.ToArray();
            guildMaster.Text = FriendsList.guildMaster;
            guildOfficersList.Lines = FriendsList.guildOffis.ToArray();
            guildMembersList.Lines = FriendsList.guildMembers.ToArray();
            BNetFriendsList.Lines = FriendsList.BNetFriends.ToArray();
            this.UseWaitCursor = false;
        }
        #endregion

        #region Answer Tab

        private void chb_answerFriends2_CheckedChanged(object sender, EventArgs e)
        {
            chb_answerFriends.Checked = chb_answerFriends2.Checked;
        }

        private void chb_myName_answer2_CheckedChanged(object sender, EventArgs e)
        {
            chb_myName_answer.Checked = chb_myName_answer2.Checked;
        }

        #region Random
        private void btn_addRandomAnswer_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tb_randomAnswer.Text))
                return;
            lb_randomAnswer.Items.Add(tb_randomAnswer.Text);

            tb_randomAnswer.Text = string.Empty;
        }

        private void btn_removeRandomAnswer_Click(object sender, EventArgs e)
        {
            try
            {
                if (lb_randomAnswer.Items.Count == 0 || lb_randomAnswer.SelectedItem == null)
                    return;

                lb_randomAnswer.Items.RemoveAt(lb_randomAnswer.SelectedIndex);
            }
            catch (Exception ex)
            { ShutUp_AIML.dlog("btn_removeRandomAnswer_Click \n\n{0}", ex); }
        }
        #endregion

        #endregion

        #region myName Tab

        private void tbn_myName_add_all_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tb_myName_AddName.Text) || lb_myName_all.Items.Contains(tb_myName_AddName.Text))
                return;

            lb_myName_all.Items.Add(tb_myName_AddName.Text);
        }

        private void btn_myName_add_this_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tb_myName_AddName.Text) || lb_myName_this.Items.Contains(tb_myName_AddName.Text))
                return;

            lb_myName_this.Items.Add(tb_myName_AddName.Text);
        }

        private void btn_myName_remove_all_Click(object sender, EventArgs e)
        {
            if (lb_myName_all.SelectedItem == null)
                return;

            lb_myName_all.Items.RemoveAt(lb_myName_all.SelectedIndex);
        }

        private void btn_myName_remove_this_Click(object sender, EventArgs e)
        {
            if (lb_myName_this.SelectedItem == null || lb_myName_this.SelectedItem == Me.Name)
                return;

            lb_myName_this.Items.RemoveAt(lb_myName_this.SelectedIndex);
        }

        #endregion

        #region Securities
        private void btn_GMsoundTest_Click(object sender, EventArgs e)
        {
            ChatHelper.PlaySound("GM");
        }

        private void btn_GMmsgAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tb_GMnewMsg.Text))
                return;

            if (!lbox_GMmsg.Items.Contains(tb_GMnewMsg.Text))
            {
                lbox_GMmsg.Items.Add(tb_GMnewMsg.Text);
            }
            tb_GMnewMsg.Text = string.Empty;            
        }

        private void btn_GMmsgRemove_Click(object sender, EventArgs e)
        {
            if (lbox_GMmsg.SelectedIndex < 0)
                return;

            lbox_GMmsg.Items.Remove(lbox_GMmsg.SelectedItem);
        }

        #endregion

        private void btn_updateCheck_Click(object sender, EventArgs e)
        {
            var _updateForm = new UpdateForm();
            _updateForm.Show();

            //var _myName = new myNamePopUpForm();
            //_myName.Show();
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            List<string> lstr = new List<string>();

            ShutUpSettings.Instance.useNotifyIcon = chb_NotifyIcon.Checked;
            ShutUpSettings.Instance.saveLog = chb_saveLog.Checked;

            #region friend/guild tab
            ShutUpSettings.Instance.answerWisper_Friends = chb_answerFriends.Checked;
            ShutUpSettings.Instance.softIgnoFriend = chb_softIgnoFriends.Checked;
            ShutUpSettings.Instance.softIgnoAfter = (int)softIgnoAfter.Value;
            ShutUpSettings.Instance.UseFriedlist1 = chb_FriendList1.Checked;
            ShutUpSettings.Instance.UseGuildMaster = chb_guildMaster.Checked;
            ShutUpSettings.Instance.UseGuildMembersList = chb_guildMembers.Checked;
            ShutUpSettings.Instance.UseGuildOffisList = chb_guildOfficers.Checked;
            ShutUpSettings.Instance.UseInGameFriedlist = chb_inGameFriends.Checked;
            ShutUpSettings.Instance.UseBNetFriedlist = chb_BNetFriends.Checked;

            ShutUpGlobalSettings.Instance.FriendList1 = friendsList1.Lines;
            #endregion

            #region sound tab

            lstr.Clear();
            foreach (string sfile in lb_SoundFiles.Items)
            { lstr.Add(sfile); }
            ShutUpGlobalSettings.Instance.soundFiles = lstr.ToArray();

            ShutUpSettings.Instance.SoundByFriend = chb_soundOn_Friends.Checked;
            ShutUpSettings.Instance.SoundByUnknown = chb_soundOn_unknown.Checked;
            ShutUpSettings.Instance.SoundByMyName = chb_soundOn_myName.Checked;
            ShutUpSettings.Instance.useExternalPlayer_Friends = chb_sound_ExternalPlayer_Friends.Checked;
            ShutUpSettings.Instance.useExternalPlayer_unknown = chb_sound_ExternalPlayer_unknown.Checked;
            ShutUpSettings.Instance.useExternalPlayer_myName = chb_sound_ExternalPlayer_myName.Checked;
            ShutUpSettings.Instance.selectedSoundFriends = cmb_sound_Friends.SelectedItem.ToString();
            ShutUpSettings.Instance.selectedSoundUnknown = cmb_sound_unknown.SelectedItem.ToString();
            ShutUpSettings.Instance.selectedSoundMyName = cmb_sound_myName.SelectedItem.ToString();

            ShutUpSettings.Instance.SoundLoop = (int)soundLoop.Value;
            ShutUpSettings.Instance.SoundLoopEvery = (int)soundLoopEvery.Value;
            #endregion

            #region answer tab

            lstr.Clear();
            foreach (string answer in lb_randomAnswer.Items)
            { lstr.Add(answer); }
            ShutUpGlobalSettings.Instance.randomAnswer = lstr.ToArray();


            //lstr.Clear();
            //foreach (string contain in cmb_SpecificAnswer_contain.Items)
            //{ lstr.Add(contain); }
            //ShutUpGlobalSettings.Instance.specificAnswer_contain = lstr.ToArray();

            ShutUpSettings.Instance.answerWisper_unknown = chb_answerWhisper_unknown.Checked;
            ShutUpSettings.Instance.answerAfterSec = (int)answerAfterSec.Value;
            ShutUpSettings.Instance.ignoAll = rb_ignoAll.Checked;
            ShutUpSettings.Instance.ignoXW = rb_ignoAfterX.Checked;
            ShutUpSettings.Instance.ignoNo = rb_noIgno.Checked;
            ShutUpSettings.Instance.softIgnoAfter = (int)softIgnoAfter.Value;
            ShutUpSettings.Instance.ingameIgno = chb_ingameIgno.Checked;
            ShutUpSettings.Instance.answerUseAIML = chb_Answer_AIML.Checked;
            ShutUpSettings.Instance.answerUseRnd = chb_Answer_useRnd.Checked;
            #endregion

            #region myName tab

            lstr.Clear();
            foreach (string name in lb_myName_all.Items)
            { lstr.Add(name); }
            ShutUpGlobalSettings.Instance.myName_list = lstr.ToArray();

            lstr.Clear();
            foreach (string name in lb_myName_this.Items)
            { lstr.Add(name); }
            ShutUpSettings.Instance.myName_list = lstr.ToArray();

            ShutUpGlobalSettings.Instance.myName_check_bg = chb_myName_BG.Checked;
            ShutUpGlobalSettings.Instance.myName_check_guild = chb_myName_guild.Checked;
            ShutUpGlobalSettings.Instance.myName_check_party = chb_myName_party.Checked;
            ShutUpGlobalSettings.Instance.myName_check_raid = chb_myName_raid.Checked;
            ShutUpGlobalSettings.Instance.myName_check_say = chb_myName_say.Checked;
            ShutUpGlobalSettings.Instance.myName_check_yell = chb_myName_yell.Checked;
            ShutUpSettings.Instance.myName_answer = chb_myName_answer.Checked;
            ShutUpGlobalSettings.Instance.myName_showPopUp = chb_myName_showPopUp.Checked;
            #endregion

            #region Securities

            ShutUpGlobalSettings.Instance.GM_Answer = chb_GManswerGMwhisperCheck.Checked;
            ShutUpGlobalSettings.Instance.GM_PlaySound = chb_GMsoundByGMwhisperCheck.Checked;
            ShutUpGlobalSettings.Instance.GM_Logout = chb_GMlogoutByGMwhisperCheck.Checked;
            ShutUpGlobalSettings.Instance.GM_ExtPlayer = chb_GMextPlayer.Checked;
            GMAlarmMessage.Instance.Messages = lbox_GMmsg.Items.OfType<object>().Select(o => o.ToString()).ToArray();

            //ShutUpGlobalSettings.Instance.GM_AnswerText = tb_GManswerText.Text; // oldstuff

            #endregion

            ShutUpGlobalSettings.Instance.Save();
            ShutUpSettings.Instance.Save();
            GMAlarmMessage.Instance.Save();
            ShutUp_AIML.DefMsg();
            ShutUp_AIML.slog("save settings");
            ShutUp_AIML.slogSettings();
            this.Close();
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_donate_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=AS89CTDLSBGGU");
        }

        private void btn_AnswerTest_Click(object sender, EventArgs e)
        {
            new AnswerTestForm().ShowDialog();
        }

        private void chb_answerFriends_CheckedChanged(object sender, EventArgs e)
        {
            chb_answerFriends2.Checked = chb_answerFriends.Checked;
        }

        
    }
}
